package com.lei.leetcode;

import java.util.TreeMap;

/**
 * @Author LeiXiaoLei
 * @Date 2022/8/30 10:24
 * @Version 1.0
 */
public class S_677 {
    private class Node {

        public int value;
        public TreeMap<Character, Node> next;

        public Node(int value) {
            this.value = value;
            next = new TreeMap<>();
        }

        public Node() {
            this(0);
        }
    }

    private Node root;

    public S_677() {
        root = new Node();
    }

    public void insert(String key, int val) {
        Node current = root;
        for (int i = 0; i < key.length(); i++) {
            char c = key.charAt(i);
            if (current.next.get(c) == null) current.next.put(c, new Node());
            current = current.next.get(c);
        }
        current.value = val;
    }

    public int sum(String prefix) {
        Node current = root;
        for (int i = 0; i < prefix.length(); i++) {
            char c = prefix.charAt(i);
            if (current.next.get(c) == null) return 0;
            current = current.next.get(c);
        }
        return sum(current);
    }

    private int sum(Node node) {
        if (node.next.size() == 0) return node.value;
        int res = node.value;
        for (char c : node.next.keySet()) {
            res += sum(node.next.get(c));
        }
        return res;
    }
}
